package com.cloud.observer.example;


import com.cloud.mapper.Dealer;
import com.cloud.mapper.DealerMapper;
import com.cloud.observer.annotation.ScheduledBean;
import com.netflix.eureka.EurekaServerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@ScheduledBean
public class TestScheduled {

    boolean flag = true;

//  static   String index = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//
//    static  String index2 = "0123456789";

    public static void main(String[] args) {
        String deCode= "15,17,1,9,30,5,34,14,2,9,4,4,8,11,0,7,11,25,24,28,";
        String code = de(deCode);
        System.out.println(code);
    }

    private static String de(String deCode) {
        StringBuilder sb = new StringBuilder();
        String[] deCodes = deCode.split(",");
        for (String s :deCodes){
            sb.append(map2.get(s));
        }
        return sb.toString();
    }

    static Map<String, String> map = new HashMap(){
        {
            put("A","0");
            put("B","1");
            put("D","2");
            put("C","3");
            put("E","4");
            put("F","5");
            put("P","6");
            put("G","7");
            put("R","8");
            put("S","9");
            put("Z","10");
            put("V","11");
            put("I","12");
            put("J","13");
            put("L","14");
            put("M","15");
            put("X","16");
            put("Y","17");
            put("H","18");
            put("K","19");
            put("N","20");
            put("O","21");
            put("Q","22");
            put("T","23");
            put("U","24");
            put("W","25");
            put("0","26");
            put("2","27");
            put("1","28");
            put("3","29");
            put("6","30");
            put("7","31");
            put("8","32");
            put("9","33");
            put("4","34");
            put("5","35");
        }
    };
    static Map<String, String> map2 = new HashMap(){
        {
            put("0","A");
            put("1","B");
            put("2","D");
            put("3","C");
            put("4","E");
            put("5","F");
            put("6","P");
            put("7","G");
            put("8","R");
            put("9","S");
            put("10","Z");
            put("11","V");
            put("12","I");
            put("13","J");
            put("14","L");
            put("15","M");
            put("16","X");
            put("17","Y");
            put("18","H");
            put("19","K");
            put("20","N");
            put("21","O");
            put("22","Q");
            put("23","T");
            put("24","U");
            put("25","W");
            put("26","0");
            put("27","2");
            put("28","1");
            put("29","3");
            put("30","6");
            put("31","7");
            put("32","8");
            put("33","9");
            put("34","4");
            put("35","5");
        }
    };

    @Autowired
    DealerMapper dealerMapper;

    @Autowired
    EurekaServerContext eurekaServerContext;

    @Autowired
    RedisTemplate redisTemplate;

//    @ScheduledObserver(executeCycle = 5, succeedAlert = true,
//            executeHandlerCommands = {
//                    @ExecuteHandlerCommand(value = "TestScheduledExecuteLogHandler",
//                            name = "testScheduledErrorLogHandler",
//                            type = ErrorEnum.LOG),
//            },
//            successHandlerCommands = {
//                    @SuccessHandlerCommand(value = "ding.token",
//                            name = "testScheduledSuccessHandler",
//                            type = ErrorEnum.DING)
//            }, exceptionHandlerCommands = {
//            @ExceptionHandlerCommand(value = "",
//                    name = "testScheduledErrorLogHandler",
//                    type = ErrorEnum.DING)
//    }
//    )
//    @ScheduledBalance
//    @Scheduled(cron = "0/5 * * * * ? ")
    public String test() throws Exception {
//        String prefix = "bottle-"+"*";
//       Set<String> set =  redisTemplate.keys(prefix);
//        File re = new File("/Users/libin/分布");
//        List<String> list = new ArrayList<>();
//       for (String s: set){
//           redisTemplate.delete(s);
//       }
//       writeFile(re.getPath(),list);
//        String code= "HTTPS://AAX1.CN/7FKYHJKM62PWGYULB5HA";
//        code = getCode(code);
//        String last = code.substring(code.length() - 2, code.length());
//        Date d = new Date();
//        boolean b = redisTemplate.opsForSet().isMember("bottle-"+calculateSetKey(last), code);
//        Date d2 = new Date();
//        System.out.println(b + "----"+String.valueOf(d2.getTime()-d.getTime()));
//
//
//        Date d3 = new Date();
//        boolean b2 = redisTemplate.opsForSet().isMember("bottle-0", "11");
//        Date d4 = new Date();
//        System.out.println(b2 + "----"+String.valueOf(d3.getTime()-d4.getTime()));

//        if (!flag) {
//            return "12";
//        }
//        flag = false;
//        File[] file = new File("/Users/libin/fsdownload").listFiles();
//        for (File f : file) {
//            Scanner scanner = new Scanner(f);
//            Set<String> codes = new HashSet<>();
//            while (scanner.hasNextLine()) {
//                String line = scanner.nextLine();
//                String[] lines = line.split(",");
//                String code = lines[0];
//                code = code.substring(code.indexOf("HTTPS://AAX1.CN/"));
//                codes.add(getCode(code));
//                if(codes.size()  == 100000){
//                    System.out.println(codes.size());
//                    write(codes);
//                    codes.clear();
//                }
//            }
//            if(!codes.isEmpty()){
//                write(codes);
//            }
//        }


//        redisTemplate.opsForSet().add("aaa","11111111111");
        System.out.println("-------->开始执行");
//        PeerAwareInstanceRegistry pp = eurekaServerContext.getRegistry();
//        Applications a = pp.getApplications();
//        List<Application> list = a.getRegisteredApplications();
//        list.forEach(application -> {
//            List<InstanceInfo> infos = application.getInstances();
//            infos.stream().forEach(instanceInfo -> {
//                System.out.println(instanceInfo.getAppName() + "-->" + instanceInfo.getId());
//            });
//        });
        Dealer dealer = dealerMapper.selectByPrimaryKey(1);

//        Thread.sleep(50000);
        System.out.println("-------->结束执行");
        return dealer.getCode();
    }

    public static String getCode(String urlCode) {
        if (urlCode.toUpperCase().startsWith("HTTP")) {
            String[] code = urlCode.split("/");
            return code[code.length - 1];
        } else {
            return urlCode;
        }
    }


    public static String calculate(String s) {
        char[] chars = s.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (char c : chars
        ) {
            String a = map.get(String.valueOf(c));
            stringBuilder.append(a+",");
        }
        return stringBuilder.toString();
    }


    public void write(Collection<String> codes){
        redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                redisConnection.openPipeline();
                codes.stream().forEach(b -> {
                    String last = b.substring(b.length() - 3, b.length());
                    String key = "bottle-" + calculate(last);
                    String value = calculate(b);
                    redisConnection.sAdd(key.getBytes(), value.getBytes());
                });
                redisConnection.closePipeline();
                return null;
            }
        });
    }

    public static void writeFile(String filePath, Collection<String> lineList)throws Exception {
        File copy = new File(filePath.substring(0,filePath.lastIndexOf("/")));
//        File copy = new File(filePath);
        if (!copy.exists()) {
            copy.mkdirs();
        }
        try {
            FileOutputStream fout = new FileOutputStream(filePath, true);
            for (String string : lineList) {
                fout.write(string.getBytes("utf-8"));
            }
            fout.flush();
            fout.close();
        } catch (Exception e) {
            throw e;
        }
    }

}
